package com.zds.passwordbox;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.zds.passwordbox.common.Constant;
import com.zds.passwordbox.common.util.AccountIconUtil;
import com.zds.passwordbox.data.dao.AccountDao;
import com.zds.passwordbox.data.dao.DBHelper;
import com.zds.passwordbox.data.dao.domain.UserAccount;
import com.zds.passwordbox.fragment.TipDialog;

import org.apache.commons.lang3.StringUtils;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class NormalAccountActivity extends AppCompatActivity {

    private boolean isEditState;
    private int actionType;
    private boolean isHidden = true;

    private UserAccount userAccount;
    private AccountDao accountDao;

    private Toolbar toolbar;
    private EditText typeText;
    private AutoCompleteTextView detailUsername;
    private EditText detailPassword;
    private ImageView accountIcon;
    private TableLayout accountTypeTable;

    private long id = -1L;
    boolean userKeyExist = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_normal_account);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        userKeyExist = getSharedPreferences(Constant.USER_SETTING_NAME,
                Context.MODE_PRIVATE).getBoolean(Constant.USER_KEY, false);
        if (!userKeyExist) {
            new TipDialog("请先设置个人密钥").show(getSupportFragmentManager(), "tip");
        }
        // 获取数据库
        DBHelper dbHelper = DBHelper.getInstance(NormalAccountActivity.this, Constant.DB_NAME);
        accountDao = AccountDao.getInstance(dbHelper.open());
        toolbar = findViewById(R.id.detail_toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();

        userAccount = new UserAccount();
        this.userAccount.setType(0);
        if (bundle != null) {
            actionType = bundle.getInt("actionType");
            id = bundle.getLong("id");
            userAccount.setId(id);
            invalidateOptionsMenu();
        }
        typeText = findViewById(R.id.detail_account_type);
        accountIcon = findViewById(R.id.detail_account_icon);
        detailUsername = findViewById(R.id.detail_username);
        detailPassword = findViewById(R.id.detail_password);
        registerTextChangeListener();

        // 设置账户下拉选择框的选项数据
        List<String> usernameList = accountDao.queryUsernames(null);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line, usernameList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        detailUsername.setAdapter(adapter);
        detailUsername.setThreshold(1);

        setLeftDrawable(typeText, ContextCompat.getDrawable(this, R.mipmap.type));
        setLeftDrawable(detailUsername, ContextCompat.getDrawable(this, R.mipmap.default_account));
        setLeftDrawable(detailPassword, ContextCompat.getDrawable(this, R.mipmap.password));

        ImageView showHidePassword = findViewById(R.id.showHidePassword);
        showHidePassword.setOnClickListener(v -> {
            isHidden = !isHidden;
            if (isHidden) {
                detailPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            } else {
                detailPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }
            detailPassword.setSelection(detailPassword.getText().length());
        });

        // 新增
        if (actionType == 1) {
            userAccount = new UserAccount();
            this.userAccount.setType(0);
            // 初始化TableLayout
            initData();
        }
        // 其它情况都当作查看
        else {
            // 获取初始数据
            initQueryData(id);
        }

    }

    private void setLeftDrawable(EditText editText, Drawable drawable) {
        if (drawable == null) return;
        drawable.setBounds(0, 0, 70, 70);
        editText.setCompoundDrawables(drawable, null, null, null);
    }

    private void registerTextChangeListener() {

        typeText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                userAccount.setTypeText(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
                userAccount.setTypeText(s.toString());
                Integer iconR = AccountIconUtil.getIconR(userAccount.getTypeText());
                accountIcon.setImageResource(iconR == null ? R.mipmap.default_account : iconR);
            }
        });
        detailUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                userAccount.setUsername(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
                userAccount.setUsername(s.toString());
            }
        });
        detailPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                userAccount.setSecret(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
                userAccount.setSecret(s.toString());
            }
        });
    }

    // 查看状态下，初始化各个数据
    private void initQueryData(long id) {
        userAccount = accountDao.queryOne(id);
        typeText.setText(userAccount.getTypeText());
        detailUsername.setText(userAccount.getUsername());
        detailPassword.setText(userAccount.getSecret());
        Integer iconR = AccountIconUtil.getIconR(userAccount.getTypeText());
        accountIcon.setImageResource(iconR == null ? R.mipmap.default_account : iconR);
        typeText.setFocusableInTouchMode(false);
        detailUsername.setFocusableInTouchMode(false);
        detailPassword.setFocusableInTouchMode(false);
        // 清除layout中的内容
        if (accountTypeTable != null) {
            accountTypeTable.removeAllViewsInLayout();
        }
    }

    private void initData() {
        accountTypeTable = findViewById(R.id.account_type_table);
        Map<String, Integer> accountImgMap = Constant.accountImgMap;
        int columnNum = 5;
        int rowNum = (int) Math.ceil((double) accountImgMap.size() / columnNum);
        Iterator<Map.Entry<String, Integer>> iterator = accountImgMap.entrySet().iterator();
        for (int row = 0; row < rowNum; row++) {
            TableRow tableRow = new TableRow(NormalAccountActivity.this);
            tableRow.setBackgroundColor(Color.WHITE);
            for (int column = 0; column < columnNum; column++) {
                if (!iterator.hasNext()) {
                    break;
                }
                Map.Entry<String, Integer> next = iterator.next();
                ImageView imageView = new ImageView(NormalAccountActivity.this);
                imageView.setImageResource(next.getValue());
                // 设置ImageView的样式
                TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(
                        TableRow.LayoutParams.WRAP_CONTENT,
                        TableRow.LayoutParams.WRAP_CONTENT);
                // 进一步设置ImageView的具体大小，比如设置固定宽度和高度
                layoutParams.width = 130;
                layoutParams.height = 130;
                layoutParams.leftMargin = layoutParams.rightMargin = 30;
                layoutParams.bottomMargin = 30;
                imageView.setLayoutParams(layoutParams);
                imageView.setOnClickListener(view -> {
                    this.userAccount.setTypeText(next.getKey());
                    ImageView accountIcon = findViewById(R.id.detail_account_icon);
                    accountIcon.setImageResource(next.getValue());
                    typeText.setText(next.getKey());
                });
                tableRow.addView(imageView);
            }
            accountTypeTable.addView(tableRow);
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.account_detail, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (actionType == 1) {
            toolbar.setTitle("新增账户");
            menu.findItem(R.id.edit_btn).setVisible(false);
            menu.findItem(R.id.confirm_btn).setVisible(true);
            menu.findItem(R.id.cancel_btn).setVisible(false);
        } else if (isEditState) {
            toolbar.setTitle("编辑账户");
            menu.findItem(R.id.edit_btn).setVisible(false);
            menu.findItem(R.id.confirm_btn).setVisible(true);
            menu.findItem(R.id.cancel_btn).setVisible(true);
        } else {
            toolbar.setTitle("账户详情");
            menu.findItem(R.id.edit_btn).setVisible(true);
            menu.findItem(R.id.confirm_btn).setVisible(false);
            menu.findItem(R.id.cancel_btn).setVisible(false);
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        if (item.getItemId() == R.id.edit_btn) {
            isEditState = true;
            // 表示Android的菜单内容已更改，应重新绘制菜单,
            // 此方法是操作系统调用 onPrepareOptionsMenu() 的信号
            invalidateOptionsMenu();
            if (typeText != null && detailUsername != null && detailPassword != null) {
                typeText.setFocusableInTouchMode(true);
                detailUsername.setFocusableInTouchMode(true);
                detailPassword.setFocusableInTouchMode(true);
            }
            // 初始化TableLayout
            initData();
        } else if (item.getItemId() == R.id.confirm_btn) {
            if (!userKeyExist) {
                new TipDialog("请先设置个人密钥").show(getSupportFragmentManager(), "tip");
                return false;
            }
            if (StringUtils.isBlank(userAccount.getTypeText())
                    || StringUtils.isBlank(userAccount.getUsername())) {
                new TipDialog("账户类型或者用户名不能为空！").show(getSupportFragmentManager(), "tip");
                return false;
            }
            Intent resultIntent = new Intent();
            if (actionType == 1) {
                accountDao.encryptedInsert(userAccount);
                resultIntent.putExtra("handleType", 1);
                setResult(Activity.RESULT_OK, resultIntent);
                finish();
            } else if (isEditState) {
                accountDao.update(userAccount);
                resultIntent.putExtra("handleType", 2);
                setResult(Activity.RESULT_OK, resultIntent);
                finish();
            }
        } else if (item.getItemId() == R.id.cancel_btn) {
            isEditState = false;
            invalidateOptionsMenu();
            initQueryData(id);
            accountTypeTable.removeAllViewsInLayout();
        } else {
            return super.onOptionsItemSelected(item);
        }
        return true;
    }
}